//
//  HPRegisterViewController.m
//  HPZZTong
//
//  Created by Handpay on 14-3-25.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPRegisterViewController.h"
#import "HPConditionTextField.h"
#import "ZZTongNetEngine.h"
#import "ZZTongUtility.h"
#import "ZZTongColorDefine.h"
@interface HPRegisterViewController ()

@property(nonatomic, retain)HPConditionTextField* accountTextField;
@property(nonatomic, retain)HPConditionTextField* pwdTextField;
@property(nonatomic, retain)HPConditionTextField* rePwdTextField;
@property(nonatomic, retain)HPConditionTextField* mobileTextField;
@property(nonatomic, retain)HPConditionTextField* verifyCodeTextField;
@property (retain, nonatomic) IBOutlet UIButton *protocolButton;

@end

@implementation HPRegisterViewController

#define kAccountTag     0
#define kPasswordTag    1
#define kRePasswordTag  2
#define kMobileTag      3
#define kVerifyCodeTag  4

#define ERRORTIPS            @"6-20位字母和数字的组合"

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
//        self.canSave = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    self.title = @"注册";
    [super viewDidLoad];
    
    self.registerTableView.dataSource = self;
    self.registerTableView.scrollEnabled = NO;
    
    [self.registerButton setBackgroundImage:[[UIImage imageNamed:@"bluebutton.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateNormal];
    
    [self.registerButton setBackgroundImage:[[UIImage imageNamed:@"bluebuttonhover.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateHighlighted];
    
    self.agreeButton.selected = YES;
    
    NSString* title = kProtocolTitle;
    [self.protocolButton setTitle:title forState:UIControlStateNormal];
    [self.protocolButton setTitle:title forState:UIControlStateHighlighted];
    
    UILabel* label = self.protocolButton.titleLabel;
    [label sizeToFit];
    CGRect buttonFrame = self.protocolButton.frame;
    buttonFrame.size.width = label.frame.size.width + 6;
    self.protocolButton.frame = buttonFrame;
    
    if(kVerChannel == VerChannelHeXin){
        label.textColor = kTitleTipsColor;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}

- (UITableViewCell *)initTableViewCell:(int)index{
//    int tag = index + kAccountTag;
    
    UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    UILabel* desLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 44)];
    desLabel.textColor = kNormalFontColor;
    desLabel.font = kNormalFont;
    
    HPConditionTextField* textField = [[HPConditionTextField alloc] initWithFrame:CGRectMake(110, 0, 200, 44)];
    textField.textColor = kNormalFontColor;
    textField.font = kNormalFont;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    switch (index) {
        case kAccountTag:
            desLabel.text = @"账号";
            textField.placeholder = ERRORTIPS;
            textField.maxLength = 20;
            self.accountTextField = textField;
            break;
        case kPasswordTag:
            desLabel.text = @"输入密码";
            textField.placeholder = ERRORTIPS;
            textField.secureTextEntry = YES;
            textField.maxLength = 20;
            self.pwdTextField = textField;
            break;
        case kRePasswordTag:
            desLabel.text = @"确认密码";
            textField.secureTextEntry = YES;
            textField.maxLength = 20;
            self.rePwdTextField = textField;
            break;
        case kMobileTag:
            desLabel.text = @"手机号码";
            textField.conditionType = HPConditionType_Numeric;
            textField.maxLength = 11;
            self.mobileTextField = textField;
            break;
        case kVerifyCodeTag:
            desLabel.text = @"短信验证码";
            textField.conditionType = HPConditionType_Numeric;
            textField.maxLength = 6;
            self.verifyCodeTextField = textField;
            
            UIButton* getVerifyButton = [UIButton buttonWithType:UIButtonTypeCustom];
            getVerifyButton.frame = CGRectMake(215, 2, 100, 40);
            [getVerifyButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            UIColor* color = kVerChannel == VerChannelHeXin ? [UIColor whiteColor] : kNormalFontColor;
            [getVerifyButton setTitleColor:color forState:UIControlStateNormal];
            [getVerifyButton setBackgroundImage:[[UIImage imageNamed:@"smallbutton.png"] stretchableImageWithLeftCapWidth:6 topCapHeight:0] forState:UIControlStateNormal];
            [getVerifyButton addTarget:self action:@selector(getVerifyButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            getVerifyButton.titleLabel.font = kNormalFont;
            [cell addSubview:getVerifyButton];
            
            textField.frame = CGRectMake(110, 0, 105, 44);
            break;
        default:
            break;
    }
    
    [cell addSubview:desLabel];
    [desLabel release];
    
    [cell addSubview:textField];
    [textField release];
    
    return [cell autorelease];
}

- (void)getVerifyButtonClick:(UIButton*)button{
    if (![ZZTongUtility checkIsInput:self.mobileTextField tips:@"手机号码"]) {
        return;
    }
    
    if (![ZZTongUtility checkMobile:self.mobileTextField.text tips:@"请输入正确的手机号码"]) {
        return;
    }
    
    ZZTongClientEngine* zzt = [ZZTongClientEngine sharedInstance];
    
    NSDictionary* params = @{KEY_ACTION:@"register", KEY_ACCOUNT:DES_ENC(self.mobileTextField.text), KEY_CHANNEL: [zzt getChannel]};
    [zzt doSendVerifyCode:params withButton:button];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self initTableViewCell:indexPath.row];
}

- (void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respData{
    if ([action isEqualToString:NET_ACTION_REGISTER]){
        [HPUIENG removeWaiting];
        NSDictionary* params = @{KEY_ACCOUNT: self.accountTextField.text, @"mobile": self.mobileTextField.text};
        self.canSave = NO;
        [HPUIENG showScreen:SCR_REGISTER_SUCCESS params:params];
        
        ZZT_CLIENG.accountInfo.account = self.accountTextField.text;
        ZZT_CLIENG.accountInfo.mobile = self.mobileTextField.text;
        ZZT_CLIENG.accountInfo.accountStatus = AccountStatusNotSubmit;
        
        [HPCLIENTENG SaveRMSData:KEY_USER_NAME withStr:self.accountTextField.text];
    }
}

- (void)dealloc {
    self.accountTextField = nil;
    self.pwdTextField = nil;
    self.rePwdTextField = nil;
    self.mobileTextField = nil;
    self.verifyCodeTextField = nil;
    
    [_registerTableView release];
    [_registerButton release];
    [_agreeButton release];
    [_protocolButton release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setRegisterTableView:nil];
    [self setRegisterButton:nil];
    [self setAgreeButton:nil];
    [super viewDidUnload];
}

- (IBAction)agreeButtonClick:(id)sender {
    UIButton *button = (UIButton*)sender;
    button.selected = !button.selected;
}

- (IBAction)protocolButtonClcik:(id)sender {
    //跳转服务协议页面
    self.canSave = YES;
    NSString* title = kProtocolTitle;
    NSDictionary* params = @{@"title": title,
                             @"url": @"ServiceAgreements"};
    [HPUIENG showScreen:SCR_HELP params:params];
}

- (IBAction)registerButtonClick:(id)sender {
    if (![ZZTongUtility checkIsInput:self.accountTextField tips:@"账号"]) {
        return;
    }
    
    if (![ZZTongUtility checkIsInput:self.pwdTextField tips:@"密码"]) {
        return;
    }
    
    if (![ZZTongUtility checkIsInput:self.rePwdTextField tips:@"确认密码"]) {
        return;
    }
    
    if (![ZZTongUtility checkIsInput:self.mobileTextField tips:@"手机号码"]) {
        return;
    }
    
    if (![ZZTongUtility checkIsInput:self.verifyCodeTextField tips:@"短信验证码"]) {
        return;
    }
    
    NSString* accountErrorTips = [@"账号请输入" stringByAppendingString:ERRORTIPS];
    NSString* account = self.accountTextField.text;
    if ([Utility checkChar:account type:HPCharType_Alpha]
        || [Utility checkChar:account type:HPCharType_Number]
        || ![Utility checkChar:account type:HPCharType_Alphanumeric]) {
        [HPUIENG showAlert:accountErrorTips];
        return;
    }
    
    if (![ZZTongUtility checkLength:self.accountTextField tips:accountErrorTips minLen:6 maxLen:20]) {
        return;
    }
    
    NSString* pwdErrorTips = [@"密码请输入" stringByAppendingString:ERRORTIPS];
    NSString* pwd = self.pwdTextField.text;
    if ([Utility checkChar:pwd type:HPCharType_Alpha]
        || [Utility checkChar:pwd type:HPCharType_Number]
        || ![Utility checkChar:pwd type:HPCharType_Alphanumeric]) {
        [HPUIENG showAlert:pwdErrorTips];
        return;
    }
    
    if (![ZZTongUtility checkLength:self.pwdTextField tips:pwdErrorTips minLen:6 maxLen:20]) {
        return;
    }
    
    NSString* rePwd = self.rePwdTextField.text;
    if (![pwd isEqualToString:rePwd]) {
        [HPUIENG showAlert:@"两次输入的密码不一致，请重新输入"];
        return;
    }
    
    if (![ZZTongUtility checkMobile:self.mobileTextField.text tips:@"请输入正确的手机号码"]) {
        return;
    }
    
    if (![ZZTongUtility checkLength:self.verifyCodeTextField tips:@"请输入6位短信验证码" minLen:6 maxLen:6]) {
        return;
    }
    
    NSString* title = kProtocolTitle;
    title = [@"请先同意" stringByAppendingString:title];
    if (!self.agreeButton.selected) {
        [HPUIENG showAlert:title];
        return;
    }
  
    [self.accountTextField resignFirstResponder];
    [self.pwdTextField resignFirstResponder];
    [self.rePwdTextField resignFirstResponder];
    [self.mobileTextField resignFirstResponder];
    [self.verifyCodeTextField resignFirstResponder];
    
    
    ZZTongClientEngine* zzt = [ZZTongClientEngine sharedInstance];
  
    NSDictionary* params = @{KEY_ACCOUNT: DES_ENC(account),
                             @"pwd": DES_ENC(pwd),
                             KEY_ACTION: @"register",
                             KEY_VERIFYCODE: self.verifyCodeTextField.text,
                             KEY_PHONE: DES_ENC(self.mobileTextField.text),
                              KEY_CHANNEL:[zzt getChannel]};
    LOG(@"params:%@", params);
#if ZZT_FOR_TEST
    [self responseCallBackSuccess:NET_ACTION_REGISTER withData:nil];
#else
    [zzt.netEngine sendRequest:NET_ACTION_REGISTER withParams:params withDelegate:self];
    [zzt.uiEngine showNetWaiting];
#endif
}

@end
